package io.kiki.sba.registry.server.clientInterface.remoting.handler;

import io.kiki.sba.registry.api.Channel;
import io.kiki.sba.registry.common.model.Node;
import io.kiki.sba.registry.common.model.metaserver.cleaner.AppRevisionSlice;
import io.kiki.sba.registry.common.model.metaserver.cleaner.AppRevisionSliceRequest;
import io.kiki.sba.registry.common.model.slot.func.Crc32cSlotFunction;
import io.kiki.sba.registry.server.shared.remoting.AbstractClientHandler;
import io.kiki.sba.registry.store.api.repository.AppRevisionRepository;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.HashSet;
import java.util.Set;
import java.util.concurrent.Executor;
import java.util.concurrent.ThreadPoolExecutor;

public class AppRevisionSliceHandler extends AbstractClientHandler<AppRevisionSliceRequest> {

    @Autowired
    protected AppRevisionRepository appRevisionJdbcRepository;
    @Autowired
    ThreadPoolExecutor metaNodeExecutor;

    @Override
    protected Node.NodeType getConnectNodeType() {
        return Node.NodeType.central_control;
    }

    @Override
    public Object doHandle(Channel channel, AppRevisionSliceRequest request) {
        Set<String> revisions = new HashSet<>();
        Crc32cSlotFunction crc32cSlotFunction = new Crc32cSlotFunction(request.getSlotNum());
        for (String revision : appRevisionJdbcRepository.availableRevisions()) {
            if (crc32cSlotFunction.slotOf(revision) == request.getSlotId()) {
                revisions.add(revision);
            }
        }
        return new AppRevisionSlice(revisions);
    }

    @Override
    public Class interest() {
        return AppRevisionSliceRequest.class;
    }

    @Override
    public Executor getExecutor() {
        return metaNodeExecutor;
    }
}
